package com.imagine.dal;

import com.google.common.base.Strings;
import com.imagine.common.Global;
import com.imagine.entity.AccountStock;
import com.imagine.entity.Delegation;
import com.imagine.entity.Stock;
import com.imagine.service.AgentService;
import com.imagine.service.impl.AgentServiceImpl;
import com.imagine.utils.EncodingUtils;
import com.imagine.utils.HttpUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.test.context.ContextConfiguration;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.*;


/**
 * Created by liangyue on 2017/9/19.
 */
@EnableScheduling
@Component
public class QuerySinaStocks {

    private Stock stock;

    public Stock querySinaStocks(String searchStockCode) throws IOException{
        String urlStr ="http://hq.sinajs.cn/list=" + searchStockCode;
        URL url = null;
        try {
            url = new URL(urlStr);
            BufferedReader reader=null;

            //如果不加上GBK编码方式会出现编码错误
            reader=new BufferedReader(new InputStreamReader(url.openStream(), "gbk"));
            String str;
            while((str=reader.readLine())!= null){
                if(!stockNotExist(str)){
                    List<String> list;
                    list = handleStockCode(str);
                    addStock(list, searchStockCode);
                    return stock;
                }
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Scheduled(cron = "0 0/5 * * * ? ")
//    @Scheduled(cron = "0 0/1 9-17 * * ? ")
    public ArrayList<Stock> updateBestStocks() throws IOException{
        System.out.println("hahahah");
        String[] strings1 = Global.allStockCodes1;
        ArrayList<Stock> resultList = Global.arrayList;
        ArrayList<Stock> allList = new ArrayList<>();
        for (int i = 0; i < strings1.length; i++) {
            try {
                Stock stock = querySinaStocks(strings1[i]);
                if (stock == null){
                    continue;
                }
                allList.add(stock);

            } catch (IOException e) {
                e.printStackTrace();
            }
            Collections.sort(allList, new Comparator<Stock>() {

                @Override
                public int compare(Stock o1, Stock o2) {
                    if (o1 == null || o2 == null){
                        return 1;
                    }
                    double i2 = o2.getCurrentPrice()-o2.getTodayClosePrice();
                    double i1 = o1.getCurrentPrice()-o1.getTodayClosePrice();


                    if (i2 - i1 >= 0) {
                        return 1;
                    } else {
                        return -1;
                    }
                }
            });
        }

        if (resultList.isEmpty()){
            for (int i = 0; i < 10; i ++){
                resultList.add(allList.get(i));
            }
        }
        else {
            for (int i = 0; i < 10; i ++){
                resultList.set(i, allList.get(i));
            }
        }


        System.out.println(resultList.toArray().toString());

        return resultList;
    }

    public List<String> handleStockCode(String stockInfo){
        List<String> codes = null ;

        int end = stockInfo.indexOf(";") ;
        stockInfo = stockInfo.substring(0,end-3) ;
        int start = stockInfo.lastIndexOf("=") ;
        stockInfo = stockInfo.substring(start) ;
        stockInfo = stockInfo.substring(stockInfo.indexOf("\"")+1,stockInfo.length()-1) ;
        codes = Arrays.asList(stockInfo.split(",")) ;
        return codes ;
    }

    boolean stockNotExist(String stockInfo){
        int start = stockInfo.indexOf("\"");
        int end = stockInfo.lastIndexOf("\"");
        stockInfo = stockInfo.substring(start, end);
        if (stockInfo.length() < 100){
            return true;
        }
        else{
            return false;
        }

    }

    public void addStock(List<String> list, String stockCode){
        stock = new Stock();
        stock.setStockCode(stockCode);
        stock.setStockName(list.get(0));
        stock.setTodayOpenPrice(Double.parseDouble(list.get(1)));
        stock.setTodayClosePrice(Double.parseDouble(list.get(2)));
        stock.setCurrentPrice(Double.parseDouble(list.get(3)));
        stock.setTodayHighestPrice(Double.parseDouble(list.get(4)));
        stock.setTodayLowestPrice(Double.parseDouble(list.get(5)));
        stock.setBidPrice(Double.parseDouble(list.get(6)));
        stock.setSellPrice(Double.parseDouble(list.get(7)));
        stock.setTradedStockesNum(Long.parseLong(list.get(8)));
        stock.setTradedStocksAmount(Double.parseDouble(list.get(9)));
        stock.setBuyFirstApplyStocksNum(Long.parseLong(list.get(10)));
        stock.setBuyFirstPrice(Double.parseDouble(list.get(11)));
        stock.setBuySecondApplyStocksNum(Long.parseLong(list.get(12)));
        stock.setBuySecondPrice(Double.parseDouble(list.get(13)));
        stock.setBuyThirdApplyStocksNum(Long.parseLong(list.get(14)));
        stock.setBuyThirdPrice(Double.parseDouble(list.get(15)));
        stock.setBuyFourthApplyStocksNum(Long.parseLong(list.get(16)));
        stock.setBuyFourthPrice(Double.parseDouble(list.get(17)));
        stock.setBuyFifthApplyStocksNum(Long.parseLong(list.get(18)));
        stock.setBuyFifthPrice(Double.parseDouble(list.get(19)));

        stock.setSellFirstApplyStocksNum(Long.parseLong(list.get(20)));
        stock.setSellFirstPrice(Double.parseDouble(list.get(21)));
        stock.setSellSecondApplyStocksNum(Long.parseLong(list.get(22)));
        stock.setSellSecondPrice(Double.parseDouble(list.get(23)));
        stock.setSellThirdApplyStocksNum(Long.parseLong(list.get(24)));
        stock.setSellThirdPrice(Double.parseDouble(list.get(25)));
        stock.setSellFourthApplyStocksNum(Long.parseLong(list.get(26)));
        stock.setSellFourthPrice(Double.parseDouble(list.get(27)));
        stock.setSellFifthApplyStocksNum(Long.parseLong(list.get(28)));
        stock.setSellFifthPrice(Double.parseDouble(list.get(29)));
        stock.setCurrentDate(list.get(30));
        if (list.size() == 32){
            stock.setCurrentTime(list.get(31));
        }
    }

    public static String gb2312ToUtf8(String str) {
        String urlEncode = "" ;
        try {

            urlEncode = URLEncoder.encode (str, "UTF-8" );
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return urlEncode;
    }

    public int querySinaStockImage(String searchStockCode) throws Exception{
        //    http://image.sinajs.cn/newchart/daily/n/sh601006.gif
        int result = 0;
        System.out.println("/////////////////////////////"+searchStockCode);

        //读取日K图
        String kdayUrl ="http://image.sinajs.cn/newchart/daily/n/" + searchStockCode + ".gif";
        byte[] dailyImg = getImageFromNetByUrl(kdayUrl);
        if(null != dailyImg && dailyImg.length > 0){
            System.out.println("读取到日k线：" + dailyImg.length + " 字节");
            String fileName = "daily.gif";
            writeImageToDisk(dailyImg, fileName);
        }else{
            System.out.println("没有读取到日k线");
            result = -1;
        }

        String minUrl ="http://image.sinajs.cn/newchart/min/n/" + searchStockCode + ".gif";
        byte[] minImg = getImageFromNetByUrl(minUrl);
        if(null != minImg && minImg.length > 0){
            System.out.println("读取到日k线：" + minImg.length + " 字节");
            String fileName = "min.gif";
            writeImageToDisk(minImg, fileName);
        }else{
            System.out.println("没有读取到日k线");
            result = -1;
        }



        String weeklyUrl ="http://image.sinajs.cn/newchart/weekly/n/" + searchStockCode + ".gif";
        byte[] weeklyImg = getImageFromNetByUrl(weeklyUrl);
        if(null != weeklyImg && weeklyImg.length > 0){
            System.out.println("读取到周k线：" + weeklyImg.length + " 字节");
            String fileName = "weekly.gif";
            writeImageToDisk(weeklyImg, fileName);
        }else{
            System.out.println("没有读取到周k线");
            result = -1;
        }


        String monthlyUrl ="http://image.sinajs.cn/newchart/monthly/n/" + searchStockCode + ".gif";
        byte[] monthImg = getImageFromNetByUrl(monthlyUrl);
        if(null != monthImg && monthImg.length > 0){
            System.out.println("读取到月k线：" + monthImg.length + " 字节");
            String fileName = "monthly.gif";
            writeImageToDisk(monthImg, fileName);
        }else{
            System.out.println("没有读取到月k线");
            result = -1;
        }
        return result;
    }

    /**
     * 将图片写入到磁盘
     * @param img 图片数据流
     * @param fileName 文件保存时的名称
     */
    public static void writeImageToDisk(byte[] img, String fileName){
        try {
            String absolutePath = QuerySinaStocks.class.getResource("/").getPath();
            String needPath = absolutePath.substring(0,absolutePath.indexOf("W"));
            File file = new File(needPath +"image/"+ fileName);
            FileOutputStream fops = new FileOutputStream(file);
            fops.write(img);
            fops.flush();
            fops.close();

            System.out.println("图片已经写入到硬盘");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 根据地址获得数据的字节流
     * @param strUrl 网络连接地址
     * @return
     */
    public static byte[] getImageFromNetByUrl(String strUrl){
        try {
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(5 * 1000);
            InputStream inStream = conn.getInputStream();//通过输入流获取图片数据
            byte[] btImg = readInputStream(inStream);//得到图片的二进制数据
            return btImg;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 从输入流中获取数据
     * @param inStream 输入流
     * @return
     * @throws Exception
     */
    public static byte[] readInputStream(InputStream inStream) throws Exception{
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while( (len=inStream.read(buffer)) != -1 ){
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }
}



